package mvc.view;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.text.DecimalFormat;

import javax.swing.JLabel;
import javax.swing.JPanel;

import mvc.controller.MouseController;
import mvc.model.ModelCurve;

import org.geom.Point2D;
import org.geom.Point3D;
import org.geom.curve.ICurve;
import org.render.IRenderer;


/** JPanel is used as a Canvas object for drawing curve. **/
public class ViewCurve extends JPanel implements IRenderer{

	/**
	 * 0
	 */
	private static final long serialVersionUID = 1L;
	
	protected ICurve model;
	protected Graphics graphic;
	protected IRenderer renderer;
	
	protected DecimalFormat df = new DecimalFormat("0.00");

	
	//---------------------------------------------------------------------- constructor
	public ViewCurve(ModelCurve model, IRenderer r, Dimension d, String title)  {
		super();
		initJPanel(d, title);
		
		this.model = model;
		this.renderer = r;
		this.graphic = this.getGraphics();
		
		model.addView(this);
	}

	private void initJPanel(Dimension d, String title) {
		//System.out.println("ViewCurve > init > title: "+title+" and dimension: "+d.toString());
		
		JLabel jtitle = new JLabel(title);
		
		setPreferredSize(d);
		setBackground(new Color(255,255,255));
		
		add(jtitle);
		
	}

	//---------------------------------------------------------------------- view

	@Override
	public void paintComponent(Graphics g) {
		//System.out.println("View > overrided paintComponent");
		graphic = g;
		updateFromModel();
		render(model, g);
	}	

	public void addMouseController(MouseController listener) {		
		addMouseListener(listener);
		addMouseMotionListener(listener);
		addKeyListener(listener);
	}

	public void updateFromModel() {
		//System.out.println("ViewCurve > updateFromModel > model: "+model + " renderer: "+renderer);
		if (graphic!=null) {
			super.paintComponent(graphic); 			// clear the screen
			//renderer.render(model, graphic);
		}
	}
	
	public void updateFromController() {
		
	}
	
	//---------------------------------------------------------------------- renderer delegation
	// metodi usati quando il controller agisce direttamente sul renderer e non sul model 
	// per esempio nella rotazione, scala, traslazione
	
	public void render(ICurve curve, Graphics g) {
		renderer.render(curve, g);
	}

	public void setRotate(int x, int y) {
		renderer.setRotate(x, y);
	}

	public void setScale(int x, int y) {
		renderer.setScale(x, y);
	}

	public void setTranslate(int x, int y) {
		renderer.setTranslate(x, y);
	}
	
	public ViewCurve setTranslate(int x, int y, boolean foo) {
		this.setTranslate(x, y);
		return this;
	}
	
	public Point2D getTranslate() {
		return renderer.getTranslate();
	}

	public Point2D transform3dTo2d(Point3D p) {
		return renderer.transform3dTo2d(p);
	}

}
